$(document).ready(function(){
	var type=$('#type').val();
	var deptId=$('#deptId').val();
	//初始化form表单
	initForm(type,deptId);
	
	//事件绑定
	eventBind(type,deptId);
});

//初始化form表单
function initForm(type,deptId){
	$('#deptForm').validation();
	
	if(type=='add'){
		//初始化科室类型下拉框
		genDictSelect('deptTypeInfo','department_type','1');
		//初始化门诊住院属性下拉框
		genDictSelect('deptOutpatienAttrInfo','outpatient_attr','1');
		//初始化所属医院级拉框
		initParentSel(null);
	}else{
		$.getApiClient('/baseInfo/department/{id}').setQuery({id: deptId}).get().done(function(data){
			if(data.code=='0'){
				var payload=data.payload;
				$('#deptForm').bindData(payload);
				$('#department_code').attr('readonly','readonly');
				//初始化科室类型下拉框
				genDictSelect('deptTypeInfo','department_type',payload.department_type);
				//初始化门诊住院属性下拉框
				genDictSelect('deptOutpatienAttrInfo','outpatient_attr',payload.department_type);
				initParentSel(payload.hospital_id);
			}
		})
	}
	
	//初始化所属医院级拉框
	function initParentSel(defaultVal){
		$.getApiClient('/baseInfo/hospitals').setQuery({}).get().done(function(data){
			if(!data.payload){
				data.payload=[];
			}
		    multipleSelectData("hospital_id",[{"id": "", "hospital_name": "请选择"}].concat(data.payload), defaultVal, {valueAttr:'id', displayAttr:'hospital_name'},'请选择');
			$('#hospital_id').multipleSelect({width:'100%', single: true});
		});
	}
}

//事件绑定
function eventBind(type,deptId){
	$('#cancel').click(function(){
		BootstrapDialog.closeAll();
	})
	
	if(type=='add'){
		$('#save').on('click',saveNewDepartment);
	}else{
		$('#save').on('click',function(){
			updateDepartment(deptId);
		});
	}
}

//新增科室操作
function saveNewDepartment(){
	if(!$("#deptForm").validationForm()){
		return;
	}
	
	$.getApiClient('/baseInfo/department').post('#deptForm', function(params){
		return $.extend(params, {
			hospital_name: $('#hospital_id').multipleSelect('getSelects','text')[0]
		});
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','保存成功',null,2000);
			pageQuery();
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//修改科室操作
function updateDepartment(deptId){
	if(!$("#deptForm").validationForm()){
		return;
	}
	
	$.getApiClient('/baseInfo/department/{id}').setQuery({
		id:deptId
	}).put('#deptForm', function(params){
		return $.extend(params, {
			hospital_name: $('#hospital_id').multipleSelect('getSelects','text')[0]
		});
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','修改成功',null,2000);
			pageQuery();
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}